package com.jijia.webbase.utils;

import cn.hutool.json.JSONUtil;

import lombok.extern.slf4j.Slf4j;


import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WebSocketUtil {
    public static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();


    public static void sendMessage(Session session,String message){
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Async async = session.getAsyncRemote();
        if (async == null) {
            return;
        }
        try {
            async.sendText(message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //获取所有的在线用户 遍历发送给所有在线用户
    public static void sendMessageToAllOnlineUser(String message){
        List<Long> userIds = new ArrayList<>();
        //获取所有的key 加入到 userIds
        for (String key : sessions.keySet()) {
            userIds.add(Long.valueOf(key));
        }
        for (Session session : sessions.values()) {
            sendMessage(session, JSONUtil.toJsonStr(userIds));
        }
    }
}
